package com.sdy.resdir.task.iporder;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.approval.api.ApprovalAllApi;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.mvc.annotation.TaskSync;
import com.sdy.resdir.biz.mapper.RdIpUpdateApplicationMapper;
import com.sdy.resdir.biz.model.*;
import com.sdy.resdir.biz.service.RdIpChangeService;
import com.sdy.resdir.biz.service.RdResourceDirService;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.DeptDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 定时查询数据库中待审批的IP订单并且发送给流程审批模块
 *
 * @author hyh
 */
@Component
@Slf4j
public class IpOrderTask {

    @Resource
    private RdIpUpdateApplicationMapper ipOrderMapper;
    @Autowired
    private ApprovalAllApi approvalAllApi;
    @Autowired
    private RdIpChangeService rdIpChangeService;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private RdResourceDirService rdResourceDirService;
    @Value("${res.app.code}")
    private String appCode;
    @Value("${res.dept.code}")
    private String deptCode;
    @Value("${res.approval.authCode}")
    private String authCode;
    @Value("${res.approval.roleCode}")
    private String roleCode;

    /**
     * 定时查询是否有IP修改申请单需要发送至流程审批模块进行审批，如果有，则发送至流程审批模块
     */
    @Scheduled(cron = "0/30 * * * * ?")
    @TaskSync
    public void sendIpOrderList() throws Exception {
        // 查询出需要发送到流程审批模块的订单
        List<RdIpUpdateApplication> ipOrderList = ipOrderMapper.selectList(Wrappers.<RdIpUpdateApplication>lambdaQuery().eq(RdIpUpdateApplication::getCurrentState, 2));
        if (!ipOrderList.isEmpty()) {
            List<Map<String, Object>> sendList = new ArrayList<>();
            List<String> ipChangeIds = ipOrderList.stream().map(RdIpUpdateApplication::getIpId).collect(Collectors.toList());
            Assert.isTrue(ipChangeIds.isEmpty(), "无法获取ip变动列表");
            for (RdIpUpdateApplication order : ipOrderList) {
                // 所有的ipchange
                String ipIdString = order.getIpId();
                if (StringUtil.isNotBlank(ipIdString)) {
                    String[] split = ipIdString.split(",");
                    List<String> ipList = new ArrayList<>(Arrays.asList(split));
                    List<RdIpChange> rdIpChangeList = rdIpChangeService.list(new LambdaQueryWrapper<RdIpChange>().in(RdIpChange::getId, ipList));
                    for (RdIpChange rdIpChange : rdIpChangeList) {
//                        if (order.getIpId().equals(rdIpChange.getId().toString())) {
                        // 受限资源生成订单时用来区分审批部门的部门id
                        List<Integer> resSourceDeptIdList = new ArrayList<>();
                        // 资源的受限公开情况
                        List<Integer> resPowerList = new ArrayList<>();
                        Integer resPower = null;
                        if (StringUtil.isNotBlank(rdIpChange.getNewResIdList())) {
                            String[] resIds = rdIpChange.getNewResIdList().split(",");
                            List<RdResourceDir> resList = rdResourceDirService.list(new LambdaQueryWrapper<RdResourceDir>().in(RdResourceDir::getId, resIds));
                            if (!resList.isEmpty()) {
                                resSourceDeptIdList = resList.stream().map(RdResourceDir::getResSourceDeptId).collect(Collectors.toList());
                                resPowerList = resList.stream().map(RdResourceDir::getResPower).collect(Collectors.toList());
                                resPower = resPowerList.get(0);
                            }
                        } else {
                            if (StringUtil.isNotBlank(rdIpChange.getOldResIdList())) {
                                String[] resIds = rdIpChange.getOldResIdList().split(",");
                                List<RdResourceDir> resList = rdResourceDirService.list(new LambdaQueryWrapper<RdResourceDir>().in(RdResourceDir::getId, resIds));
                                if (!resList.isEmpty()) {
                                    resSourceDeptIdList = resList.stream().map(RdResourceDir::getResSourceDeptId).collect(Collectors.toList());
                                    resPowerList = resList.stream().map(RdResourceDir::getResPower).collect(Collectors.toList());
                                    resPower = resPowerList.get(0);
                                }
                            }
                        }
                        DeptDto deptBase = userQueryApi.getDeptByCode(deptCode);
                        Integer deptBaseId = deptBase.getId();
                        Integer sourceDeptId = null;
                        int approvalUserId = userQueryApi.getRoleByCode(roleCode).getId();
                        if (resPower != null && resPower == 2) {
                            DeptDto dept = userQueryApi.getDept(resSourceDeptIdList.get(0));
                            sourceDeptId = dept.getId();
                        }
                        if (StringUtil.isNotBlank(rdIpChange.getNewResIdList())) {
                            rdIpChange.getNewResIdList().split(",");
                        }
                        Map<String, Object> map = new HashMap<>(16);
                        map.put("order_item_no", order.getApplyNum());
                        map.put("res_id", "[资源目录]-IP" + rdIpChange.getNewResIdList());
                        map.put("user_id", order.getApplyUserId());
                        map.put("resPower", resPower);
                        map.put("deptBaseId", deptBaseId);
                        map.put("sourceDeptId", sourceDeptId);
                        map.put("approvalUserId", approvalUserId);
                        sendList.add(map);
                        // 修改订单状态为已发送
                        order.setCurrentState(3);

                    }
                }
            }
            // 查询当前是否存在资源目录ip修改申请流程,如果没有则创建该流程
            int updateOrder = ipOrderMapper.batchUpdate(ipOrderList);
            Integer lookResId = 0;
            if (!sendList.isEmpty()) {
                lookResId = approvalAllApi.ipUpdateOrderCreate(sendList);
            }
            if (updateOrder == 0 || lookResId == 0) {
                log.error("向流程审批模块发送IP修改单数据时出现异常");
            }
        }

    }

}
